package com.lengjing.project.controller;

import com.lengjing.project.common.MsgReturn;
import com.lengjing.project.model.User;
import com.lengjing.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description :
 * @Author : ChenYao
 * @Version : 1.0
 * @Create : Date Time: 2018/6/23 11:09
 * @Update : Date Time: 2018/6/23 11:09
 * @see :
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * @Description: 获取所有用户信息
     * @Author: ChenYao
     * @param:
     * @return: html
     * @throws:
     * @see: Note:
     */

    @GetMapping("hello")
    public String hello(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("hello", "<h1>你好</h1>");
        request.setAttribute("hello", map);
        return "userManage";
    }

    /**
     * @Description: 测试连接用的
     * @Author: ChenYao
     * @param:
     * @return:
     * @throws:
     * @see: Note:
     */

    @GetMapping("test")
    @ResponseBody
    public String test() {
        return "OK";
    }

    /**
     * @Description: 测试成功的请求, 返回success.html页面, 由thymeleaf自动配置, classpath:/templates/
     * @Author: $ChenYao
     * @param:
     * @return: success.html
     * @throws:
     * @see: Note:
     */

    @GetMapping("success")
    public String success() {
        return "success";
    }

    @GetMapping(value = "getUserList")
    @ResponseBody
    public MsgReturn getUserList(Integer page, Integer count) {
        return userService.getUserList(page, count);
    }

    /**
     * @Description: 登录接口
     * @Author: ChenYao
     * @param: [user, map, session]
     * @returns: java.lang.String
     * @throws:
     * @CreateDate: 2018/6/26 15:33
     * @see: Note:
     */

    @PostMapping("login")
    public String login(User user, Map<String, Object> map, HttpSession session) {
        if (!StringUtils.isEmpty(user.getUsername()) && !StringUtils.isEmpty(user.getPassword())) {
            //登录查询,返回用户信息
            User loginUser = userService.login(user);
            if (loginUser ==null){
                map.put("msg", "用户名或密码错误");
                return "login";
            }
            session.setAttribute("loginUser", loginUser);
            return "redirect:/main.html";
        }
        map.put("msg", "用户名或密码错误");
        return "login";
    }
}
